package com.liuhung.ash.resource.controller;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.liuhung.ash.resource.entity.Res;
import com.liuhung.ash.resource.service.ResService;
import com.liuhung.base.util.FileUtil;
import com.liuhung.base.util.Md5Util;
import com.liuhung.base.util.PropUtil;
/**
 * @author liuhung
 * 本实例为Dropzone 实现的后端上传代码。并将上传信息存储于数据库以备后查
 */
@Controller
@RequestMapping(value = "/upload")
public class UploadController {
	
	private static final Logger logger = Logger.getLogger(UploadController.class);
	
	@Autowired(required=false) //自动注入，不需要生成set方法了，required=false表示没有实现类，也不会报错。
	private ResService resService; 

	@RequestMapping(value = "/dropzone")
	@ResponseBody
	public Res upload(@RequestParam(value = "file", required = false) MultipartFile file,
			HttpServletRequest request, ModelMap model) {
		Res um = new Res();
		try {
			logger.info("---------------- upload img begin ---------------------");
			// 文件是否为空
			if (file.getSize() == 0 || file.isEmpty()) {
				um.setStatus(0);
				um.setMsg("上传文件不能为空");
				return um;
			}
			// 文件是否过大
			if (file.getSize() > PropUtil.UPLOAD_MAXSIZE) {
				um.setStatus(0);
				um.setMsg("抱歉，上传文件过大，请上传小于"+(PropUtil.UPLOAD_MAXSIZE/1024)+"K的文件");
				return um;
			}

			String path = FileUtil.getSavePath(PropUtil.DEFAULT_UPLOAD_PATH);
			String ori_fileName = file.getOriginalFilename();
			String md5_fileName = Md5Util.getFileMD5String(file.getInputStream()) + "."
					+ FileUtil.getExtensionName(ori_fileName);
			logger.info("path:" + path);
			logger.info("ori_fileName:" + ori_fileName);
			logger.info("md5_filename:" + md5_fileName);
			File pathFile = new File(path);
			if(!pathFile.exists()&&!pathFile.isDirectory())
			{
				pathFile.mkdirs();
			}
			File targetFile = new File(path, md5_fileName);
			if (!targetFile.exists()) {
				file.transferTo(targetFile);
				// 是否是图片
				if (!isImage(targetFile)) {
					targetFile.delete();
					um.setStatus(0);
					um.setMsg("抱歉，请上传jpg、png、gif、dmp等图片类型文件");
					return um;
				}
			}
			String url =PropUtil.DEFAULT_UPLOAD_URL+path.replace(PropUtil.DEFAULT_UPLOAD_PATH, "")+md5_fileName;
			um.setStatus(1);
			um.setMsg("上传成功");
			um.setOldname(ori_fileName);
			um.setMd5name(md5_fileName);
			um.setSavepath(path);
			um.setUrl(url);
			resService.add(um);
		} catch (Exception e) {
			logger.error(e);
			um.setStatus(0);
			um.setMsg(" upload false " + e);
		}
		logger.info("---------------- upload img end ---------------------");
		return um;
	}
	/**
	 * 判断文件是否是图片
	 * @param file
	 * @return
	 * @throws IOException 
	 */
	private static boolean isImage(File file) throws IOException {
		BufferedImage bi = ImageIO.read(file);
		if(bi == null){
		   return false;
		}
		return true;
	}
	
	
	
}
